<?php 
/**
 * 产品管理
 * @copyright   Copyright (c) 2006 - 2010 DZH 德卓恒常发2号
 * @category   	基本信息
 * @package  	Model
 * @author    	李恺弘
 * @version 	2.1,2012-07-22
 */

class ProductPublicModel extends RelationModel {
	/// 模型名与数据表名不一致，需要指定
	protected $tableName = 'product';
	/// 自动验证设置
	protected $_validate	 =	 array(
	 
			array("product_no",'require','require',1),
			array("product_no",'','unique',1,'unique'),
			array("product_no",'/^[0-9a-zA-Z\-]+$/',"格式为英文或数字或横杠！",1),
			array("product_no",'validbarcode','',1,'callbacks'), 	 
			array("product_name",'require','require',1),
			array("product_name",'','unique',1,'unique'),
///			array("capability","orders_norms",'require',0,'ifcheck','',1), 
			array("capability",'require',"require",0),
			array("capability",'pst_integer',"pst_integer",0),
///			array("dozen","orders_norms",'require',0,'ifcheck','',1), 
			array("dozen",'require',"require",0),
			array("dozen",'pst_integer',"pst_integer",2),
///			array("p_s_3","orders_norms",'pst_integer',0,"ifcheck",1),
///			array("p_s_3",'require',"require",0), 	
			array("p_s_3",'pst_integer',"p_s_err",2), 	
			array("product_class_id",'require','require',1),
			array("factory_id",'require','require',0),
			array("instock_price",'require','require',2),
			array("instock_price",'double',"double",2), 
			array("sale_price",'double',"double",2), 
			array("wholesale_price",'double',"double",2), 
			array("retail_price",'double',"double",2),  
			array("cube_long",'double',"p_s_err",2), 	
			array("cube_wide",'double',"p_s_err",2), 	
			array("cube_high",'double',"p_s_err",2), 	
			array("weight",'double',"p_s_err",2), 	
		);
		
	///关联插入	 
	public $_link = array('product_color' => array(
						  						'mapping_type'	=> HAS_MANY,												
												'class_name'	=> 'product_color',
												'foreign_key'	=> 'product_id', 
						  				),
						  'product_size' => array(
						  						'mapping_type'	=> HAS_MANY,												
												'class_name'	=> 'product_size',
												'foreign_key'	=> 'product_id', 
						  				),
						 	
						  'product_class_info' => array(
						  						'mapping_type'	=> HAS_ONE,												
												'class_name'	=> 'product_class_info',
												'foreign_key'	=> 'product_id', 
						  				), 'product_detail' => array(
						  						'mapping_type'	=> HAS_MANY,												
												'class_name'	=> 'product_detail',
												'foreign_key'	=> 'product_id', 
						  				),	
					  	  'product_fit' => array(
						  						'mapping_type'	=> HAS_ONE,												
												'class_name'	=> 'product_fit',
												'foreign_key'	=> 'product_id', 
					  				),															
						);
	
	 
	/**
	 * 整理POST数组 多选框值以字符串入库
	 *
	 * @param array $data
	 * @return array
	 */
	public function setPost($data) {	
		if (empty($data))	$data	=	$_POST; 
		foreach ($data['product_detail'] as &$value) {
			if (is_array($value['value'])) {
				$value['value'] = @implode(',',$value['value']);
			}
		}
		$product_color = $product_size = null;
		foreach ((array)$data['size'] as $key => $size_id) {
			$product_size[]['size_id'] = $size_id;
		}
		foreach ((array)$data['color'] as $key => $color_id) {
			$product_color[]['color_id'] = $color_id;
		}
		(empty($product_color) && !empty($data['id'])) && M('ProductColor')->where('product_id='.$data['id'])->delete();
		(empty($product_size) && !empty($data['id'])) && M('ProductSize')->where('product_id='.$data['id'])->delete();
		$data['product_color'] = $product_color;
		$data['product_size'] = $product_size;
		$data['product_class_info'] = $this->getProductClassInfo($data['product_class_id']);
		$data['product_fit']['fit'] = json_encode($data['fit']);  
		return $data;
	}
	
	/**
	 * 获取产品信息
	 *
	 * @param int $product_class_id
	 * @return array
	 */
	public  function getProductClassInfo($product_class_id) {
		$info = array();
		$model	=	D('ProductClass'); 
		if (C('PRODUCT_CLASS_LEVEL')==1) {
			$info['class_1'] = $product_class_id;
		}elseif (C('PRODUCT_CLASS_LEVEL')==2) {
			$info['class_2'] = $product_class_id;
			$temp = $model->field('parent_id')->find($product_class_id); 
			$info['class_1'] = $temp['parent_id'];
		}elseif (C('PRODUCT_CLASS_LEVEL')==3) {
			$info['class_3'] = $product_class_id;
			$temp = $model->field('parent_id')->find($product_class_id);
			$info['class_2'] = $temp['parent_id'];
			$temp = $model->field('parent_id')->find($temp['parent_id']);
			$info['class_1'] = $temp['parent_id'];
		}elseif (C('PRODUCT_CLASS_LEVEL')==4) {
			$info['class_4'] = $product_class_id;
			$temp = $model->field('parent_id')->find($product_class_id); 
			$info['class_3'] = $temp['parent_id'];
			$temp = $model->field('parent_id')->find($temp['parent_id']);
			$info['class_2'] = $temp['parent_id'];
			$temp = $model->field('parent_id')->find($temp['parent_id']);
			$info['class_1'] = $temp['parent_id'];
		}
		return $info;
	}
	 
	/**
	 * 取产品列表
	 */
	public function getIndexList(){
		$order	= $_REQUEST['_sort']!=1?' product_no desc':' product_no';
		if($_POST['pics']==1) {
			$gallery_exists	= 'select 1 from gallery where relation_id=product.id and relation_type=1';
		}
		$count 	= $this->exists('select 1 from product_class_info where product_id=product.id and '.getWhere($_POST['class']))->exists($gallery_exists)->where(getWhere($_POST['main']))->count();
		$this->setPage($count);
		$ids	= $this->field('id')->exists('select 1 from product_class_info where product_id=product.id and '.getWhere($_POST['class']))->exists($gallery_exists)->where(getWhere($_POST['main']))->order($order)->page()->selectIds();
		$info['from'] 	= 'product a left join product_class_info b on(a.id=b.product_id) left join gallery c on(a.id=c.relation_id and c.relation_type=1)';
		$info['group'] 	= ' group by a.id order by '.$order;
		$info['where'] 	= ' where a.id in'.$ids;
		$info['field'] 	= 'a.*,b.class_1,b.class_2,b.class_3,b.class_4';
		$sql =  'select '.$info['field'].' from '.$info['from'].$info['where'].$info['group'];
		return _formatList($this->query($sql),$this->_default_format);
	}
	
	
	/**
	 * 取产品明细
	 *
	 * @param  $id 产品ID
	 * @param  string $type操作类型,edit修改，view查看，查看时需编译属性值
	 * @return array $rs
	 */
	public function getInfo($id,$type='edit') { 
		if ($type=='edit') {
			$rs = self::getEditRs($id);
			$rs['factory_readonly'] = false;
			/// 产品关联厂家判断厂家是否可修改
			if (C('PRODUCT_FACTORY')) { 
					$count = M('Orders')->where('factory_id='.$rs['factory_id'])->count();
					if ($count>0) {
						$rs['factory_readonly'] = true;
					} 
					if ($rs['factory_readonly']==false){
						$count = M('InstockDetail')->where('factory_id='.$rs['factory_id'])->count();	
						if ($count>0) {
							$rs['factory_readonly'] = true;
						} 
					} 
			}
		}else {
			$rs = self::getViewRs($id);
		}
		$rate = self::getRate(); 
		$model	=	D('Gallery'); 
		$rs['pics'] = $model->getAry($id,1); 
		return $rs;
	}
	
	/**
	 * 取修改产品时的明细信息
	 *
	 * @param int $id 产品ID
	 * @return array
	 */
	private function getEditRs($id) {
		$product_id = $id;
		$rs 	= _formatArray(M('Product')->field('*,cube_high*cube_wide*cube_long as cube')->find($id));/// 取主表信息  
		$detail = M('ProductDetail')->where('product_id='.$id)->formatFindAll(array('key'=>'properties_id'));/// 取明细信息
		/// 取产品入库价格信息
		$p_price = M('ProductPrice')->where('product_id='.$id)->find();
		$temp = M('Currency')->where('to_hide=1')->order('id asc')->select();
		foreach ($temp as $value) {
			$rs['price']['last'][$value['currency_no']] = $p_price['last_price_'.$value['id']];
			$rs['price']['avg'][$value['currency_no']] = $p_price['avg_price_'.$value['id']];
		}
		/// 取在用的产品属性信息
		$userInfo	= getUser();
		$role_type	= $userInfo['role_type'];
		$role_type_where = ($role_type ==1||$_SESSION[C('ADMIN_AUTH_KEY')]==true) ? " " : " and  role_type in (1,".$role_type.")";
		$properties = M('Properties')->field('id as properties_id,properties_no,properties_name,properties_name_fr,properties_type')->where('to_hide=1'.$role_type_where)->formatFindAll(array('key'=>'properties_id'));
		foreach ($properties as $id => &$var) {
			$var['product_id'] 	= $detail[$id]['product_id'];
			$var['value'] 		= $detail[$id]['value'];
			$var['id'] 			= $detail[$id]['id'];
		}
		!empty($properties) && $rs['detail'] = $properties;
		/// 取颜色信息
		if (C('PRODUCT_COLOR')) {
			$temp = M('ProductColor')->where('product_id='.$rs['id'])->field('color_id')->select();
			if (!empty($temp)) {
				foreach ($temp as $value) {
					$rs['color'][] = $value['color_id'];
				}
				 $rs['color'] = implode(',',$rs['color']);
			}
		}
		/// 取尺码信息
		if (C('PRODUCT_SIZE')) {
			$temp = M('ProductSize')->where('product_id='.$rs['id'])->field('size_id')->select();
			if (!empty($temp)) {
				foreach ($temp as $value) {
					$rs['size'][] = $value['size_id'];
				}
				 $rs['size'] = implode(',',$rs['size']);
			}
		}
		$fit 				= M('ProductFit')->where('product_id='.$product_id)->find();  
///		echo $pci->getLastSql();
		$rs['fit'] 				= json_decode(htmlspecialchars_decode($fit['fit']),true);
		$rs['product_id_name']	= $this->getPareantClassName($product_id);  
		return $rs;
	}
	
	/**
	 * 取查看产品时的明细信息
	 *
	 * @param int $id 产品ID
	 * @return array
	 */
	private function getViewRs($id) {
		$product_id = $id;
		$rs 	= _formatArray(M('Product')->field('*,cube_high*cube_wide*cube_long as cube')->find($id));/// 取主表信息  
		$detail = M('ProductDetail')->where('product_id='.$id)->formatFindAll(array('key'=>'properties_id'));/// 取明细信息
		/// 取产品入库价格信息
		$p_price = M('ProductPrice')->where('product_id='.$id)->find();
		$temp = M('Currency')->where('to_hide=1')->order('id asc')->select();
		foreach ($temp as $value) {
			$rs['price']['last'][$value['currency_no']] = $p_price['last_price_'.$value['id']];
			$rs['price']['avg'][$value['currency_no']] = $p_price['avg_price_'.$value['id']];
		}
		/// 取在用的产品属性信息
		$userInfo	= getUser();
		$role_type	= $userInfo['role_type'];
		$role_type_where = ($role_type ==1||$_SESSION[C('ADMIN_AUTH_KEY')]==true) ? " " : " and role_type in (1,".$role_type.")";
		$properties = M('Properties')->field('id as properties_id,properties_no,properties_name,properties_name_fr,properties_type')->where('to_hide=1'.$role_type_where)->formatFindAll(array('key'=>'properties_id'));
		$_cache_proper = M('PropertiesValue')->field('id,pv_name,pv_name_fr')->formatFindAll(array('key'=>'id'));
		$lang_set = LANG_SET=='fr' ? '_fr' : '';
		foreach ($properties as $id => &$var) {
			$var['product_id'] 	= $detail[$id]['product_id'];
			$var['value'] 		= $detail[$id]['value'];
			switch ($var['properties_type']) {
				case 1:/// 自定义输入
					$var['properties_value'] = $var['value'];
				break;
				case 2:/// 单选框
					$var['properties_value'] = $_cache_proper[$var['value']]['pv_name'.$lang_set];
				break;
				case 3:/// 多选框
					if (strpos($var['value'],',')) {
						$temp = @explode(',',$var['value']);
						foreach ((array)$temp as $properties_value_id) {
							$v_ary[] = $_cache_proper[$properties_value_id]['pv_name'.$lang_set];
						}
						$var['properties_value'] = implode('，',$v_ary);
					} else {
						$var['properties_value'] = $_cache_proper[$var['value']]['pv_name'.$lang_set];
					}
				break;
			}
		}
		!empty($properties) && $rs['detail'] = $properties;
		/// 取颜色信息
		if (C('PRODUCT_COLOR')) {
			$temp = M('ProductColor')->where('product_id='.$rs['id'])->field('color_id')->select();
			if (!empty($temp)) {
				$dd_color = S('color');
				foreach ($temp as $value) {
					$rs['color'][] = $dd_color[$value['color_id']]['color_name'];
				}
				$rs['color'] = implode('，',$rs['color']);
			}
		}
		/// 取尺码信息
		if (C('PRODUCT_SIZE')) {
			$temp = M('ProductSize')->where('product_id='.$rs['id'])->field('size_id')->select();
			if (!empty($temp)) {
				$dd_size = S('size');
				foreach ($temp as $value) {
					$rs['size'][] = $dd_size[$value['size_id']]['size_name'];
				}
				$rs['size'] = implode('，',$rs['size']);
			}
		}
		$fit = M('ProductFit')->where('product_id='.$product_id)->find(); 
		$rs['fit'] = json_decode(htmlspecialchars_decode($fit['fit']),true); 
		$rs['product_id_name']	= $this->getPareantClassName($product_id);	  
		return $rs;
	}
	
	/**
	 * 获取多级类别的产品名称
	 *
	 * @param int $product_id
	 * @return string
	 */
	function getPareantClassName($product_id){ 
		if ($product_id>0){
			$pci			=	  M('product_class_info');
			$class_info 	= $pci->where('product_id='.$product_id)->field('class_1,class_2,class_3,class_4')->find();  
			$prodcut_class_dd	= 	S('product_class');
			foreach ((array)$class_info as $key=>$c_id) {
				if ($c_id>0){ 
					if ($key!='class_1'){
						$product_id_name	.=	'->';
					}
					$product_id_name	.=	$prodcut_class_dd[$c_id]['class_name'];
				} 
			}  
		}   
		return $product_id_name;	 
	}
	
	/**
	 * 获取汇率currency_from='EUR' and currency_to='RMB'
	 *
	 * @return double
	 */
	public function getRate(){
		$rate = M('RateInfo')->where("currency_from='EUR' and currency_to='RMB' and rate_date='".date('Y-m-d')."'")->getField('opened_y');
		return $rate;
	}
	
	/**
	 * 获取权限
	 *
	 * @return unknown
	 */
	public function getRole(){
		return ;
		$role = UserAction::getAuthInfo(); 
		$company_id = M('User')->where('id='.$role['user_id'])->getField('company_id');
		if ($role['user_type']==2) {
			$country = M('Company')->where('id='.$company_id)->find();
			$id = M('District')->where("district_name='中国' and parent_id=0")->getField('id');
			if ($country['country_id']==$id && $country['detail_type']) {
				if ($country['detail_type']==1) {
					return 1;
				}elseif ($country['detail_type']==2){
					return 2;
				}else return 3;
			}elseif ($country['country_id']==$id || $country['detail_type']){
				if ($country['country_id']==$id) {
					return 4;
				}elseif ($country['detail_type']==1) {
					return 5;
				}elseif ($country['detail_type']==2){
					return 6;
				}else return 7;
			}
			
			/*if ($country['country_id']==$id) {
				return 1;///国内用户
			}elseif ($country['detail_type']==1){
				return 2;///批发客户
			}elseif ($country['detail_type']==2){
				return 3;///零售客户
			}else{
				return 4;///大客户
			}*/
		}else{ ///(IS_ADMIN || SUPER_ADMIN)
			return 8;
		}
	}
	
	/**
	 * 根据产品ID取产品属性信息
	 *
	 * @param int $product_id
	 * @return array
	 */
	public function getProperties($product_id) {
		$detail = M('ProductDetail')->where('product_id='.$product_id)->formatFindAll(array('key'=>'properties_id'));/// 取明细信息
		/// 取在用的产品属性信息
		$role_type_where = (IS_ADMIN || SUPER_ADMIN || (ROLE_TYPE ==1)) ? " " : " and role_type in (1,".ROLE_TYPE.")";
		$properties = M('Properties')->field('id as properties_id,properties_no,properties_name,properties_name_fr,properties_type')->where('to_hide=1'.$role_type_where)->formatFindAll(array('key'=>'properties_id'));
		$_cache_proper = M('PropertiesValue')->field('id,pv_name,pv_name_fr')->formatFindAll(array('key'=>'id'));
		$lang_set = LANG_SET=='fr' ? '_fr' : '';
		foreach ($properties as $id => &$var) {
			$var['product_id'] 	= $detail[$id]['product_id'];
			$var['value'] 		= $detail[$id]['value'];
			switch ($var['properties_type']) {
				case 1:/// 自定义输入
					$var['properties_value'] = $var['value'];
				break;
				case 2:/// 单选框
					$var['properties_value'] = $_cache_proper[$var['value']]['pv_name'.$lang_set];
				break;
				case 3:/// 多选框
					if (strpos($var['value'],',')) {
						$temp = @explode(',',$var['value']);
						foreach ((array)$temp as $properties_value_id) {
							$v_ary[] = $_cache_proper[$properties_value_id]['pv_name'.$lang_set];
						}
						$var['properties_value'] = implode('，',$v_ary);
					} else {
						$var['properties_value'] = $_cache_proper[$var['value']]['pv_name'.$lang_set];
					}
				break;
			}
		}
		return $properties;
	}					
		
}